package com.xbongbong.saas.service.impl;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.contractproduct.pojo.dto.QuotationProductDeleteBatchDTO;
import com.xbongbong.pro.contractproduct.pojo.vo.QuotationProductDeleteBatchVO;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.quatation.pojo.QuotationProductAmountPojo;
import com.xbongbong.saas.domain.entity.QuotationProductEntity;
import com.xbongbong.saas.model.QuotationProductModel;
import com.xbongbong.saas.service.QuotationProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author long.rao
 * @version v1.0
 * @date 2019/8/16 10:16
 * @since v1.0
 */
@Service("quotationProductService")
public class QuotationProductServiceImpl implements QuotationProductService {
    private static final Logger LOG = LoggerFactory.getLogger(QuotationProductServiceImpl.class);

    @Resource
    private QuotationProductModel quotationProductModel;

    @Override
    public void dataConsistencyUpdate(String corpid, Long productId, String productName, String specification, String serialNo) throws XbbException {
        try {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("parentId", productId);
            param.put("del", 0);
            List<QuotationProductEntity> quotationProductEntities = quotationProductModel.findEntitys(param);
            for (QuotationProductEntity entity : quotationProductEntities) {
                entity.setProductName(productName);
                entity.setSpecification(specification);
                entity.setProductNo(serialNo);
                entity.setUpdateTime(DateTimeUtil.getInt());
            }
            if (!quotationProductEntities.isEmpty()) {
                quotationProductModel.dataConsistencyUpdate(quotationProductEntities, corpid);
            }
        } catch (Exception e) {
            LOG.error("QuotationProductServiceImpl.dataConsistencyUpdate 出错，corpid=" + corpid + "  productId=" + productId + "  productName=" + productName + "  specification=" + specification, e);
        }
    }

    @Override
    public QuotationProductDeleteBatchVO deleteBatch(QuotationProductDeleteBatchDTO quotationProductDeleteBatchDTO) throws XbbException {
        QuotationProductDeleteBatchVO quotationProductDeleteBatchVO = new QuotationProductDeleteBatchVO();
        try {
            List<Long> contractIdIn = quotationProductDeleteBatchDTO.getQuotationIdIn();
            String corpid = quotationProductDeleteBatchDTO.getCorpid();
            quotationProductModel.deleteQuotationAllProduct(contractIdIn, corpid);
        } catch (Exception e) {
            LOG.error("ContractProductServiceImpl.deleteBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return quotationProductDeleteBatchVO;
    }

    @Override
    public Set<Long> quotationProductByQuotationId(Set<Long> quotationIdSet, String corpid) {
        Integer del = DelEnum.NORMAL.getDel();
        Map<String, Object> quotationProductParam = new HashMap<>(3);
        quotationProductParam.put("corpid", corpid);
        quotationProductParam.put("del", del);
        quotationProductParam.put("quotationIdIn", quotationIdSet);
        List<QuotationProductEntity> quotationProductList = (List<QuotationProductEntity>) com.xbongbong.saas.toolbox.help.BasicHelper.findEntitysByImitatePage(quotationProductParam, quotationProductModel);
        Set<Long> productIdSet = new HashSet<>();
        for (QuotationProductEntity quotationProduct : quotationProductList) {
            Long productId = quotationProduct.getProductId();
            productIdSet.add(productId);
        }
        return productIdSet;
    }

    @Override
    public Map<Long, Double> getQuotationIdAvgPriceMap(Set<Long> quotationIdSet, Long productId, String corpid) {
        Integer del = DelEnum.NORMAL.getDel();
        Map<String, Object> quotationProductParam = new HashMap<>(4);
        quotationProductParam.put("corpid", corpid);
        quotationProductParam.put("del", del);
        quotationProductParam.put("quotationIdIn", quotationIdSet);
        quotationProductParam.put("productId", productId);
        List<QuotationProductEntity> quotationProductList = (List<QuotationProductEntity>) com.xbongbong.saas.toolbox.help.BasicHelper.findEntitysByImitatePage(quotationProductParam, quotationProductModel);
        Map<Long, QuotationProductAmountPojo> quotationIdProductPojoMap = new HashMap<>(quotationProductList.size());
        for (QuotationProductEntity quotationProduct : quotationProductList) {
            Long quotationId = quotationProduct.getQuotationId();
            Double price = quotationProduct.getPrice();
            Double productNum = quotationProduct.getProductNum();
            //如果价格不合法，则跳过
            if (price < 0 || productNum < 0) {
                continue;
            }
            QuotationProductAmountPojo productAmount = quotationIdProductPojoMap.get(quotationId);
            if (productAmount == null) {
                //若未加入过Pojo，则初始化
                productAmount = new QuotationProductAmountPojo(Arith.mul(price, productNum), productNum);
                quotationIdProductPojoMap.put(quotationId, productAmount);
            } else {
                //若加入过Pojo，则对金额和数量进行更新
                //更新金额
                Double amount = productAmount.getAmount();
                amount += Arith.mul(price, productNum);
                productAmount.setAmount(amount);
                //更新数量
                Double count = productAmount.getCount();
                count += productNum;
                productAmount.setCount(count);
                //放回map
                quotationIdProductPojoMap.put(quotationId, productAmount);
            }
        }
        //构建报价单id-平均价格map
        Map<Long, Double> quotationIdPriceMap = new HashMap<>(quotationProductList.size());
        for (Map.Entry<Long, QuotationProductAmountPojo> entry : quotationIdProductPojoMap.entrySet()) {
            Long quotationId = entry.getKey();
            QuotationProductAmountPojo productAmount = entry.getValue();

            Double averagePrice = Arith.div(productAmount.getAmount(), productAmount.getCount());
            quotationIdPriceMap.put(quotationId, averagePrice);
        }
        return quotationIdPriceMap;
    }
}
